﻿namespace DatabaseDoc.Library.Factories
{
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.ComponentModel.Composition.Hosting;
    using System.IO;
    using System.Linq;
    using System.Reflection;

    /// <summary>
    /// Database connector factory
    /// </summary>
    public class DatabaseConnectorFactory
    {
        /// <summary>
        /// The collection of database connectors
        /// </summary>
        [ImportMany(typeof(IDatabaseConnector))]
        private IEnumerable<IDatabaseConnector> databaseConnectors;

        /// <summary>
        /// Initializes a new instance of the <see cref="DatabaseConnectorFactory"/> class.
        /// </summary>
        public DatabaseConnectorFactory()
        {
            // http://stackoverflow.com/questions/2526423/mef-doesnt-find-parts-in-other-assemblies           
            var catalog = new DirectoryCatalog(".", "*");
            
            var container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        /// <summary>
        /// Creates the database connector.
        /// </summary>
        /// <param name="databaseTypeKey">The database type key.</param>
        /// <returns>The database connector</returns>
        public IDatabaseConnector CreateDatabaseConnector(string databaseTypeKey)
        {
            if (this.databaseConnectors == null)
            {
                return null;
            }

            var databaseConnector = this.databaseConnectors.SingleOrDefault(dc => string.Compare(dc.Key, databaseTypeKey, true) == 0);
            return databaseConnector;
        }
    }
}